<template>
  <div class="JsonToTree">
    <div class="json-left">
      <span>请输入：</span>
      <el-input
        type="textarea"
        style="width: 100%"
        v-model="json"
        class="textarea"
        :autosize="{ minRows: 15, maxRows: 30 }"
        placeholder="请输入json字符串"
        @change="whenJsonChange"
      ></el-input>
      <span style="color: red" v-show="jsonError">您输入的不是一个正确的json</span>
    </div>
    <div class="json-right">
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        height="800px"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        header-align="center"
        :header-cell-style="{ background: '#fafafa' }"
      >
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="键名" prop="key" show-overflow-tooltip align="left" />
        <el-table-column label="键值" prop="value" show-overflow-tooltip align="center" />
        <el-table-column label="描述信息" prop="desc" show-overflow-tooltip align="center" />
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'JsonToTree',
  components: {},
  data() {
    return {
      json: '{"c_mc_imei()":"614126822738457","c_mc_home_code()":"86","imsiConversionList":[{"businessId":"123","converseEndTime":"2024-07-25T14:56:34.602","converseStartTime":"2024-07-25T14:56:34.602","converseType":1,"converseUser":"881552687789904171","converseUserName":"焦山仁","createBy":"admin","createTime":"2024-07-25T14:56:34.602","id":123456,"imsi":"460605319590757","mobile":"18888888888","status":0,"sysDicts":{},"updateBy":"hh","updateTime":"2024-07-25T14:56:34.602"}],"c_mc_car_body_length()":"4.635","moblie":"17523224956","c_mc_car_plate_type_name()":"普通车牌","mpIdcardNum":"522424197610235113","c_mc_troj_end_date()":"2023-11-24 15:46:04","c_mc_job_address()":"四川省成都市仁和新城","c_mc_car_color(车牌颜色)":"蓝","zjhm":"522424197610235113","c_mc_car_base_smallimg_url(小图url路径)":"www.baidu.com/2.jpg","c_mc_housing_address()":"四川省成都市仁和新城","zplj":"www.baidu.com/1.jpg","percent":0.9563,"c_mc_troj_start_date()":"2023-11-24 15:46:04","hpys":"1","c_mc_imsi()":"460605319590757","c_mc_relation_probrability(关联概率)":"0.9563","c_mc_car_bureau_code()":"510000000000","c_mc_housing_location_list(居住地位置集合)":[{"lat":30.05473987,"lon":105.27730940}],"cUJmflag":"1","c_mc_car_body_color_code()":"7","c_mc_job_location_list(工作地位置集合)":[{"$ref":"$.c\\_mc\\_housing\\_location\\_list\\(居住地位置集合\\)[0]"}],"rljdid":"881552687789904171","mcTrojStartTime":"2023-11-24 15:46:04","c_mc_sp_code()":"1","c_mc_active_address()":"四川省成都市仁和新城","c_mc_car_base_bigimg_url(大图url路径)":"www.baidu.com/1.jpg","relationList":[{"cActiveAddress":"四川省成都市仁和新城","cActiveLocationList":[[{"lat":30.05473987,"lon":105.27730940}]],"cActiveLocationListStr":"四川省成都市仁和新城","cAreacode":"510000000000","cHomecode":"86","cHousingAddress":"四川省成都市仁和新城","cHousingLocationList":[{"$ref":"$.relationList[0].cActiveLocationList[0][0]"}],"cImei":"614126822738457","cImsi":"460605319590757","cJobAddress":"四川省成都市仁和新城","cJobLocationList":[{"$ref":"$.relationList[0].cActiveLocationList[0][0]"}],"cSpcode":"1","cUJmflag":"1","cUsernum":"17523224956","carBaseBigimgUrl":"www.baidu.com/1.jpg","carBaseSmallimgUrl":"www.baidu.com/2.jpg","createBy":"admin","createTime":"2024-07-25T14:56:34.609","csys":"7","cwkc":"4.635","cyzjdm":"1","encryptMobile":"g6gQoAhaEKjmy7ntTTRXIfQ8ErMaV/oMrqwASvk5ow/MQ7Um+ayX0s9RhQdBsbmH9xjPD5e9w4xqS0wqOEMp+95E7JlMIO0/JhRzsQF/BySKow4FV3/qPsspXhhc0EvX0/u5i60KLI35v5HzeynAXCRvBhnxWATT1/NgGClW+EY=","finalRelationProbrability":"0.9563","hphm":"川A123456","hpys":"1","hpysStr":"蓝","hpzl":"1","hpzlmc":"普通车牌","id":"123456","imsiConversionList":[{"businessId":"123","converseEndTime":"2024-07-25T14:56:34.609","converseStartTime":"2024-07-25T14:56:34.609","converseType":1,"converseUser":"881552687789904171","converseUserName":"焦山仁","createBy":"admin","createTime":"2024-07-25T14:56:34.609","id":123456,"imsi":"460605319590757","mobile":"18888888888","status":0,"sysDicts":{},"updateBy":"hh","updateTime":"2024-07-25T14:56:34.609"}],"imsiList":[],"mcCarNoColor":"蓝","mcCarNum":"川A123456","mcMobile":"123456","mcRelationProbrability":"0.9563","mcTrojEndDate":"2023-11-24 15:46:04","mcTrojEndTime":"2023-11-24 15:46:04","mcTrojStartDate":"2023-11-24 15:46:04","mcTrojStartTime":"2023-11-24 15:46:04","moblie":"17523224956","mpIdcardNum":"522424197610235113","mpPersonId":"291026944880353","percent":0.9563,"rljdid":"881552687789904171","ssgajgjgdm":"510000000000","ssgajgmc":"成都市天府新区华阳派出所","tagList":[{"archivesId":"川A123456","archivesType":2,"createBy":"admin","createTime":"2024-07-25T14:56:34.609","createUserId":123456,"hpys":"1","id":123456,"isDelete":0,"sysDicts":{},"tableId":"123456","tagId":123456,"tagName":"可疑车辆","updateBy":"hh","updateTime":"2024-07-25T14:56:34.609","userId":"123456","visibleType":3}],"updateBy":"hh","updateTime":"2024-07-25T14:56:34.609","zjhm":"522424197610235113","zplj":"www.baidu.com/1.jpg"}],"mcTrojEndTime":"2023-11-24 15:46:04","mpPersonId":"291026944880353","c_mc_car_bureau_name()":"成都市天府新区华阳派出所","hpysStr":"蓝","cActiveLocationList":[[{"$ref":"$.c\\_mc\\_housing\\_location\\_list\\(居住地位置集合\\)[0]"}]],"encryptMobile":"g6gQoAhaEKjmy7ntTTRXIfQ8ErMaV/oMrqwASvk5ow/MQ7Um+ayX0s9RhQdBsbmH9xjPD5e9w4xqS0wqOEMp+95E7JlMIO0/JhRzsQF/BySKow4FV3/qPsspXhhc0EvX0/u5i60KLI35v5HzeynAXCRvBhnxWATT1/NgGClW+EY=","cUsernum":"17523224956","tagList":[{"archivesId":"川A123456","archivesType":2,"createBy":"admin","createTime":"2024-07-25T14:56:34.609","createUserId":123456,"hpys":"1","id":123456,"isDelete":0,"sysDicts":{},"tableId":"123456","tagId":123456,"tagName":"可疑车辆","updateBy":"hh","updateTime":"2024-07-25T14:56:34.609","userId":"123456","visibleType":3}],"c_mc_active_location_list(常活动地位置集合)":"四川省成都市仁和新城","imsiList":[],"cAreacode":"510000000000","finalRelationProbrability":"0.9563","c_mc_car_plate_type()":"1","c_mc_car_num(车牌号)":"川A123456","c_mc_mobile(手机号码)":"123456","hphm":"川A123456","cyzjdm":"1"}',
      tableData: [],
      jsonError: false
    };
  },
  created() {
    this.whenJsonChange();
  },
  methods: {
    whenJsonChange() {
      this.jsonError = false;
      let obj;
      try {
        obj = new Function(`return ${this.json}`)();
        console.log(obj);
      } catch (e) {
        this.jsonError = true;
      }
      if (typeof obj === 'object' && obj) {
        this.tableData = this.convertToTreeTable(obj);
      } else {
        this.tableData = [];
        this.jsonError = true;
      }
    },
	  createId(length) {
      let returnStr = '';
      const charStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      for (let i = 0; i < length; i++) {
        let index = Math.round(Math.random() * (charStr.length - 1));
        if (i === 0) {
          index = Math.round(Math.random() * (charStr.length - 11));
        }
        returnStr += charStr.substring(index, index + 1);
      }
      return returnStr;
    },
    isArrayOrObj(data) {
	    return data instanceof Array || data instanceof Object;
    },
	  //obj是数组或者对象
	  //obj是数组或者对象
	  convertToTreeTable(obj,lastKey='') {
		  if (Array.isArray(obj)) {
			  return obj.reduce((acc, cur) => {
				  let accList=this.convertToTreeTable(cur,lastKey)
				  accList&&acc.push(...accList)
				  return acc;
			  }, [])
			  //return obj.map(t => this.convertToTreeTable(t));
		  } else if (obj instanceof Object) {
			  return Object.entries(obj).map(([key, value]) => {
				  const isSimple = !this.isArrayOrObj(value);
				  const temp = {
					  rowId: this.createId(15),
					  key,
					  children: []
				  };
				  if (lastKey) {
					  temp.groupKey = `${lastKey}.${key}`;
				  }else{
					  temp.groupKey = key;
				  }
				  if (isSimple) {
					  temp.value = value;
				  } else {
					  if(Array.isArray(value)&&!this.isArrayOrObj(value[0])){
						  temp.value=value.join(',')
					  }else{
						  let children = this.convertToTreeTable(value,key);
						  while (children?.length === 1 && Array.isArray(children[0])) {
							  children = children[0];
						  }
						  temp.children = children;
						  temp.value =temp.children.length > 0 ? '见子列表' : '-';
					  }

				  }
				  return temp;
			  });
		  }
	  }
  },
  watch: {}
};
</script>

<style scoped>
.JsonToTree {
  display: flex;
  padding: 10px;
  background-color: #ffffff;
  flex-direction: row;
  justify-content: space-between;
  height: 100%;
  width: 100%;
  overflow: hidden;
  .json-left {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 800px;
  }
  .json-right {
    height: 100%;
    margin-left: 15px;
    flex: 1;
    overflow: hidden;
  }
}
</style>
